
<?php
//function that creates a menu-list
	function createPageList(&$db) {
		$pageQuery = mysqli_query($db, "SELECT id, name, tagName, parentId, isLink FROM pages WHERE parentId='0'");
		if (session_status() == PHP_SESSION_NONE) {
			session_start();
		}
		echo "<div style=\"max-width: 40%; height: 250px; overflow:scroll\">";
		createPageListRecursive($pageQuery, $db, 0);
		echo "</div>";
	}

	//help-function that go through the DB page for page with recursion
	function createPageListRecursive(&$pageQuery, &$db, $oldRights) {
		//while we have a page to check
		while($page = $pageQuery->fetch_assoc()) {
			//SQL query that JOINS two DB to get the rights for a specific page for a single user
			$rightsQuery = mysqli_query($db, "SELECT rights FROM group_rights JOIN users ON group_rights.groupId = users.rightsId WHERE group_rights.pageId = '".$page["id"]."' AND users.username = '".$_SESSION["username"]."' LIMIT 1");	
			$right = $rightsQuery->fetch_assoc();
			$rights = $oldRights | $right["rights"];
			//if we are at start we do not want to print anything or we do not have the rights
			if(($rights&2) != 2) {
				//do nothing
			}else if($page["isLink"] == 0) { //if we do not have a link, show toggler
				echo "<li>";
				echo "<label label-default=\"\" id=\"id{$page["id"]}\" class=\"nav-header pageList\">".$page["tagName"]."</label>";
				echo "<ul class=\"nav  tree active-trial\">";
			}else{ //else we have a link
				echo "<li><label class=\"pageList\" id=\"id{$page["id"]}\">".$page["tagName"]."</label>";
			}
			
			//get the id of this nde
			$parent = $page["id"];
			//get all the children from this node
			$nextPageQuery = mysqli_query($db, "SELECT id, name, tagName, parentId, isLink FROM pages WHERE parentId='$parent'");
			//call the same function with the query of its children
			createPageListRecursive($nextPageQuery, $db, $rights);
	
			//hide if no rights
			if(($rights&2) == 2) {
		
				//if we do not have a link add a extra </ul>
				if($page["isLink"] == 0) {
					echo "</ul>";
				}
				echo "</li>";
			}
		}
	}
?>